<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use app\common\model\order\OrderAction;
use app\common\model\order\OrderGoodsModel;
use app\common\model\order\OrderModel;
use app\common\model\order\OrderStatementModel;
use app\common\model\order\OrderUniqueModel;
use app\common\model\User;
use Exception;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 订单售后管理
 *
 * @icon fa fa-circle-o
 */
class OrderRefund extends Backend
{

    /**
     * OrderRefund模型对象
     * @var \app\admin\model\order\OrderRefund
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\OrderRefund;
        $this->view->assign("moldList", $this->model->getMoldList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->images){
            $row->images = explode(',',$row->images);
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 同意
     */
    public function agree($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $status = $row->status;
        if($status != 0){
            $this->error(__('状态错误'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $params['status'] = 1; // 状态:0=待审核,1=已审核(待发货),2=待收货,3=退款成功,4=拒绝,5=取消申请
        $params['check_time'] = time();

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException(true)->validate($validate);
            }

            $order = OrderModel::get($row->order_id);
            $order->aftersale_status = 1;

            $oper = [
                'id' => $this->auth->id,
            ];
            OrderAction::operAdd($order, null, $oper, 'admin', '售后申请已通过');

            if($row->mold == 2){
                // TODO 发布任务队列
                // 消息参数
                $queueParams = [
                    'order_refund_id' => $ids,
                ];
                // 延时执行时间(秒)
                $queueTime = config('site.no_send_close_order_time') * 3600;
                $queue = 'yayiyun';
                // 后台审核通过后,用户超时未发货,关闭订单操作
                Queue('app\common\job\OrderRefundAutoOper@NoSendCloseOrder', $queueParams, $queueTime, $queue);
            }

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    /**
     * 改价
     */
    public function edit_price($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $status = $row->status;
        if($status != 0){
            $this->error(__('状态错误'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $result = false;
            Db::startTrans();
            try {
                if($row->last_refund_price == 0){
                    $params['last_refund_price'] = $row->refund_price;
                }

                $order = OrderModel::get($row->order_id);
                $order->aftersale_status = 0;
                $oper = [
                    'id' => $this->auth->id,
                ];
                OrderAction::operAdd($order, null, $oper, 'admin', '售后订单改价:'.$params['refund_price']);

                $result = $row->allowField(true)->save($params);

                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 拒绝
     */
    public function refuse($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $status = $row->status;
        if($status != 0){
            $this->error(__('状态错误'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params['status'] = 4; // 状态:0=待审核,1=已审核(待发货),2=待收货,3=退款成功,4=拒绝
            $params['check_time'] = time();
            $params['is_close'] = 1;
            $params['close_time'] = time();
            $result = false;
            Db::startTrans();
            try {
                $update = [
                    'is_sales' => 0,
                    'refund_no' => null,
                    'refund_status' => null,
                ];
                $result = \app\admin\model\order\OrderGoods::where(['id'=>$row->order_goods_id])->update($update);
                if($result){
                    $OrderGoods = \app\admin\model\order\OrderGoods::where(['order_id'=>$row->order_id])->field('id,is_sales')->select();
                    $is_sales = 0;
                    foreach ($OrderGoods as $key => $val){
                        if($val['is_sales'] > 0){
                            $is_sales += 1;
                        }
                    }
                    if($is_sales == 0){
                        $result = \app\admin\model\order\Order::where(['id'=>$row->order_id])->update(['is_sales'=>0]);
                    }
                }

                $order = OrderModel::get($row->order_id);
                $order->aftersale_status = 4;
                $oper = [
                    'id' => $this->auth->id,
                ];
                OrderAction::operAdd($order, null, $oper, 'admin', '售后申请已驳回');

                $result = $row->allowField(true)->save($params);

                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 退款完成
     */
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $status = $row->status;
        $mold = $row['mold'];
        if($mold == 2){
            if($status != 2){
                $this->error(__('状态错误'));
            }
        }else{
            if($status != 0){
                $this->error(__('状态错误'));
            }
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $params['status'] = 3; // 状态:0=待审核,1=已审核(待发货),2=待收货,3=退款成功,4=拒绝
        $params['refund_time'] = time();
        $params['is_close'] = 1;
        $params['close_time'] = time();

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException(true)->validate($validate);
            }

            // 修改订单状态
            \app\admin\model\order\OrderGoods::where(['id'=>$row->order_goods_id])
                ->update([
                    'refund_status' => 1,
                    'refund_fee' => $row->refund_price,
                    'refund_msg' => $row->cause,
                ]);

            $order = OrderModel::get($row->order_id);
            $total_order_count = \app\admin\model\order\OrderGoods::where(['order_id'=>$row->order_id])->count();
            $total_refund_order_count = \app\admin\model\order\OrderGoods::where(['order_id'=>$row->order_id,'refund_status' => 1])->count();
            if($total_order_count == $total_refund_order_count){
                $order->status = 4;
                $order->save();
            }
            $order->aftersale_status = 3;
            $order->refund_status = 1;
            $oper = [
                'id' => $this->auth->id,
            ];
            OrderAction::operAdd($order, null, $oper, 'admin', '售后退款完成');

            // 生成账单
            OrderStatementModel::operAdd('aftersales', $row);
            // 添加销售单账单的售后订单ID (因为会存在一个订单多个售后单,所以不修改)
//            OrderStatementModel::where(['order_id' => $row->order_id])->update(['refund_order_id',$row->id]);

            // 退回优惠券
            $orderUnique = OrderUniqueModel::get(['unique_order_no' => $order->unique_order_no]);
            if($orderUnique && $orderUnique->coupon_id > 0){
                $order_ids = OrderModel::where(['unique_order_no' => $orderUnique->unique_order_no])->column('id');
                $order_goods_counts = OrderGoodsModel::whereIn('id',$order_ids)->count();
                $order_goods_sales_counts = OrderGoodsModel::where(['is_sales' => ['>',0],'refund_status' => 1])->count();
                // 当所有子订单的所有商品全部售后之后,退回优惠券
                if($order_goods_counts == $order_goods_sales_counts){
                    $user_coupon = \app\common\model\UserCouponModel::get($orderUnique->coupon_id);
                    $time = time();
                    if($user_coupon->endtime <= $time){
                        // 过期了
                        \app\common\model\UserCouponModel::where(['id' => $orderUnique->coupon_id])->update(['status' => 3, 'usetime' => '']);
                    }else{
                        \app\common\model\UserCouponModel::where(['id' => $orderUnique->coupon_id])->update(['status' => 1, 'usetime' => '']);
                    }
                    $orders = OrderModel::where(['unique_order_no' => $orderUnique->unique_order_no])->select();
                    foreach ($orders as $order){
                        OrderAction::operAdd($order, null, null, 'system', '订单售后退回优惠券');
                    }
                }
            }

            $result = $row->allowField(true)->save($params);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            Db::commit();
            $this->success();
        } else {
            Db::rollback();
            $this->error(__('No rows were updated'));
        }
    }

}
